#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
阿里宝宝电商平台 - Web API服务器（简化版）
提供RESTful API接口支持前端应用
"""

from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
from datetime import datetime
import hashlib
import uuid

# 导入物流计算模块
try:
    from logistics_calculator import (
        calculate_shipping_fee_from_addresses,
        calculate_estimated_delivery_time,
        DEFAULT_WAREHOUSE_ADDRESS
    )
    LOGISTICS_AVAILABLE = True
except ImportError as e:
    print(f"警告：物流计算模块导入失败: {e}")
    LOGISTICS_AVAILABLE = False
    DEFAULT_WAREHOUSE_ADDRESS = "北京市朝阳区三里屯街道工体北路8号院"

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 加载真实商品数据
def load_real_products():
    """加载真实商品数据"""
    try:
        # 使用绝对路径获取数据文件
        data_file = "/Users/mike.chen/Desktop/伪桌面（9-10月）/贪吃蛇10.28仓库/greedy_-snakes_2-1/Greedy Snakes 2 frame/ali_bao_bao/data/商品数据集.json"
        
        with open(data_file, 'r', encoding='utf-8') as f:
            raw_products = json.load(f)
        
        # 转换数据格式
        products = []
        for i, product in enumerate(raw_products):
            # 生成商品ID
            product_id = product.get('ID', f'PROD{i+1:03d}')
            
            # 转换数据格式
            converted_product = {
                'id': product_id,
                'name': product.get('Name', '未知商品'),
                'price': float(product.get('Prize（yuan)', 0)),
                'category': product.get('Kind', 'Food'),
                'location': product.get('Province', '未知产地'),
                'merchant_id': f'SELLER{product.get("ProvinceID", 1):03d}',
                'description': f"优质{product.get('Name', '商品')}，产地{product.get('Province', '未知')}",
                'image': f"https://via.placeholder.com/300x200?text={product.get('Name', '商品')}",
                'average_rating': round(4.0 + (i % 10) * 0.1, 1),  # 4.0-4.9的评分
                'review_count': 50 + (i % 200)  # 50-249的评价数
            }
            products.append(converted_product)
        
        print(f"成功加载 {len(products)} 个真实商品")
        return products
        
    except Exception as e:
        print(f"加载真实商品数据失败: {e}")
        print(f"尝试的文件路径: {data_file}")
        print(f"文件是否存在: {os.path.exists(data_file) if 'data_file' in locals() else '未定义'}")
        # 如果加载失败，返回模拟数据
        print("使用模拟数据作为备选")
        return [
            {
                'id': 'PROD001',
                'name': '优质苹果',
                'price': 25.00,
                'category': 'Food',
                'location': '山东烟台',
                'merchant_id': 'SELLER001',
                'description': '新鲜优质苹果，口感香甜，营养丰富',
                'image': 'https://via.placeholder.com/300x200?text=苹果',
                'average_rating': 4.5,
                'review_count': 128
            }
        ]

# 加载商品数据
REAL_PRODUCTS = load_real_products()

# 用户购物车数据存储
USER_CARTS = {}

# 用户订单数据存储
USER_ORDERS = {}

# 卖家商品数据管理
SELLER_PRODUCTS_FILE = os.path.join(os.path.dirname(__file__), 'seller_products.json')
SELLER_SHOPS_FILE = os.path.join(os.path.dirname(__file__), 'seller_shops.json')
USER_CARTS_FILE = os.path.join(os.path.dirname(__file__), 'user_carts.json')  # 用户购物车数据文件
USER_ORDERS_FILE = os.path.join(os.path.dirname(__file__), 'user_orders.json')  # 用户订单数据文件

def load_seller_products():
    """加载卖家商品数据"""
    try:
        if os.path.exists(SELLER_PRODUCTS_FILE):
            with open(SELLER_PRODUCTS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载卖家商品数据失败: {e}")
        return {}

def save_seller_products(products):
    """保存卖家商品数据"""
    try:
        with open(SELLER_PRODUCTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(products, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存卖家商品数据失败: {e}")
        return False

def load_seller_shops():
    """加载卖家店铺数据"""
    try:
        if os.path.exists(SELLER_SHOPS_FILE):
            with open(SELLER_SHOPS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载卖家店铺数据失败: {e}")
        return {}

def save_seller_shops(shops):
    """保存卖家店铺数据"""
    try:
        with open(SELLER_SHOPS_FILE, 'w', encoding='utf-8') as f:
            json.dump(shops, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存卖家店铺数据失败: {e}")
        return False

def load_user_carts():
    """加载用户购物车数据"""
    try:
        if os.path.exists(USER_CARTS_FILE):
            with open(USER_CARTS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载用户购物车数据失败: {e}")
        return {}

def save_user_carts(carts):
    """保存用户购物车数据"""
    try:
        with open(USER_CARTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(carts, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存用户购物车数据失败: {e}")
        return False

def load_user_orders():
    """加载用户订单数据"""
    try:
        if os.path.exists(USER_ORDERS_FILE):
            with open(USER_ORDERS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载用户订单数据失败: {e}")
        return {}

def save_user_orders(orders):
    """保存用户订单数据"""
    try:
        with open(USER_ORDERS_FILE, 'w', encoding='utf-8') as f:
            json.dump(orders, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存用户订单数据失败: {e}")
        return False

# 加载卖家数据
SELLER_PRODUCTS = load_seller_products()
SELLER_SHOPS = load_seller_shops()
USER_CARTS = load_user_carts()  # 加载用户购物车数据
USER_ORDERS = load_user_orders()  # 加载用户订单数据

# 用户数据管理
USER_DATA_FILE = os.path.join(os.path.dirname(__file__), 'users.json')

def load_users():
    """加载用户数据"""
    try:
        if os.path.exists(USER_DATA_FILE):
            with open(USER_DATA_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载用户数据失败: {e}")
        return {}

def save_users(users):
    """保存用户数据"""
    try:
        with open(USER_DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(users, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存用户数据失败: {e}")
        return False

def hash_password(password):
    """密码哈希"""
    return hashlib.sha256(password.encode()).hexdigest()

def verify_password(password, hashed):
    """验证密码"""
    return hash_password(password) == hashed

# 加载用户数据
USERS = load_users()

# 如果没有用户数据，创建默认管理员账户
if not USERS:
    USERS = {
        'admin': {
            'user_id': 'USER001',
            'username': 'admin',
            'password': hash_password('123456'),
            'email': 'admin@example.com',
            'phone': '138-0000-0000',
            'user_type': 'Customer',
            'created_at': datetime.now().isoformat()
        }
    }
    save_users(USERS)
    print("创建默认管理员账户: admin / 123456")

@app.route('/')
def index():
    """首页 - 返回静态HTML文件"""
    return send_from_directory('.', 'index.html')

@app.route('/<path:filename>')
def static_files(filename):
    """静态文件服务"""
    return send_from_directory('.', filename)

@app.route('/api/auth/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'success': False, 'error': '用户名和密码不能为空'}), 400
        
        # 查找用户
        if username in USERS:
            user = USERS[username]
            if verify_password(password, user['password']):
                # 生成token
                token = hashlib.md5(f"{username}{datetime.now()}".encode()).hexdigest()
                
                # 返回用户信息（不包含密码）
                user_data = {
                    'user_id': user['user_id'],
                    'username': user['username'],
                    'email': user['email'],
                    'phone': user['phone'],
                    'user_type': user['user_type'],
                    'token': token
                }
                
                return jsonify({
                    'success': True,
                    'data': user_data
                })
            else:
                return jsonify({'success': False, 'error': '密码错误'}), 401
        else:
            return jsonify({'success': False, 'error': '用户不存在'}), 401
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/auth/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        phone = data.get('phone')
        user_type = data.get('userType', 'Customer')
        
        if not all([username, password, email, phone]):
            return jsonify({'success': False, 'error': '所有字段都是必填的'}), 400
        
        # 检查用户名是否已存在
        if username in USERS:
            return jsonify({'success': False, 'error': '用户名已存在'}), 400
        
        # 生成用户ID
        user_id = f"USER{len(USERS) + 1:03d}"
        
        # 创建新用户
        new_user = {
            'user_id': user_id,
            'username': username,
            'password': hash_password(password),
            'email': email,
            'phone': phone,
            'user_type': user_type,
            'created_at': datetime.now().isoformat()
        }
        
        # 保存用户
        USERS[username] = new_user
        if save_users(USERS):
            # 如果是卖家，创建店铺信息
            if user_type == 'Seller':
                shop_name = data.get('shopName', f"{username}的店铺")
                shop_id = f"SHOP{len(SELLER_SHOPS) + 1:03d}"
                
                shop_info = {
                    'shop_id': shop_id,
                    'owner_username': username,
                    'name': shop_name,
                    'description': f"欢迎来到{shop_name}，优质商品，诚信经营！",
                    'logo': f"https://via.placeholder.com/100x100?text={shop_name[:2]}",
                    'address': '待完善',
                    'phone': phone,
                    'email': email,
                    'created_at': datetime.now().isoformat(),
                    'status': 'active'
                }
                
                SELLER_SHOPS[username] = shop_info
                save_seller_shops(SELLER_SHOPS)
                
                # 初始化卖家的商品列表
                SELLER_PRODUCTS[username] = []
                save_seller_products(SELLER_PRODUCTS)
            
            # 生成token
            token = hashlib.md5(f"{username}{datetime.now()}".encode()).hexdigest()
            
            # 返回用户信息（不包含密码）
            user_data = {
                'user_id': user_id,
                'username': username,
                'email': email,
                'phone': phone,
                'user_type': user_type,
                'token': token
            }
            
            return jsonify({
                'success': True,
                'data': user_data
            })
        else:
            return jsonify({'success': False, 'error': '注册失败，请稍后重试'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/auth/logout', methods=['POST'])
def logout():
    """用户登出"""
    try:
        # 登出接口，简单返回成功
        return jsonify({
            'success': True,
            'data': {
                'message': '登出成功'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products', methods=['GET'])
def get_products():
    """获取商品列表"""
    try:
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 12))
        category = request.args.get('category')
        
        # 按分类过滤
        products = REAL_PRODUCTS
        if category:
            products = [p for p in products if p['category'] == category]
        
        # 分页
        start = (page - 1) * limit
        end = start + limit
        page_products = products[start:end]
        
        return jsonify({
            'success': True,
            'data': {
                'products': page_products,
                'total': len(products),
                'page': page,
                'limit': limit,
                'has_more': end < len(products)
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/<product_id>', methods=['GET'])
def get_product_detail(product_id):
    """获取商品详情"""
    try:
        product = next((p for p in REAL_PRODUCTS if p['id'] == product_id), None)
        
        if not product:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 扩展商品详情
        product_detail = {
            **product,
            'original_price': product['price'] * 1.2,
            'images': [
                product['image'],
                f"https://via.placeholder.com/600x400?text={product['name']}细节1",
                f"https://via.placeholder.com/600x400?text={product['name']}细节2",
                f"https://via.placeholder.com/600x400?text={product['name']}包装"
            ],
            'specifications': {
                '产地': product['location'],
                '净重': '5kg',
                '保质期': '12个月',
                '储存方式': '阴凉干燥处',
                '包装': '真空包装'
            },
            'stock': 999
        }
        
        return jsonify({
            'success': True,
            'data': product_detail
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/search', methods=['POST'])
def search_products():
    """搜索商品 - 使用模糊搜索算法"""
    try:
        data = request.get_json()
        keyword = data.get('keyword', '')
        filters = data.get('filters', {})
        
        if not keyword:
            return jsonify({'success': False, 'error': '搜索关键词不能为空'}), 400
        
        # 使用模糊搜索算法
        results = fuzzy_search_products(keyword, REAL_PRODUCTS)
        
        # 应用额外过滤器
        if filters.get('category'):
            results = [p for p in results if p.get('category', '').lower() == filters['category'].lower()]
        
        if filters.get('min_price'):
            results = [p for p in results if p.get('price', 0) >= filters['min_price']]
        
        if filters.get('max_price'):
            results = [p for p in results if p.get('price', 0) <= filters['max_price']]
        
        return jsonify({
            'success': True,
            'data': {
                'products': results,
                'total': len(results),
                'keyword': keyword
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

def fuzzy_search_products(keyword: str, products: list) -> list:
    """高级模糊搜索商品 - 支持智能字符级模糊匹配和噪音过滤"""
    keyword = keyword.lower().strip()
    results = []
    
    # 过滤噪音字符
    noise_chars = ['子', '的', '了', '在', '是', '和', '有', '就', '与', '等', '或']
    
    # 如果搜索关键词是单个噪音字符，直接返回空结果
    if len(keyword) == 1 and keyword in noise_chars:
        return []
    
    for p in products:
        score = 0
        name_lower = p.get('name', '').lower()
        
        # 第一级：完整匹配
        if keyword in name_lower:
            if name_lower == keyword:
                score += 100  # 完全匹配
            elif name_lower.startswith(keyword):
                score += 80   # 开头匹配
            else:
                score += 50  # 包含匹配
        
        # 第二级：字符级模糊匹配
        else:
            max_consecutive_match = 0
            
            # 查找最长连续子串匹配
            for i in range(len(keyword)):
                for j in range(i + 1, len(keyword) + 1):
                    substring = keyword[i:j]
                    if substring in name_lower:
                        max_consecutive_match = max(max_consecutive_match, len(substring))
            
            # 连续子串匹配
            if max_consecutive_match >= 1:
                match_ratio = max_consecutive_match / len(keyword)
                score += int(30 * match_ratio)
                
                # 过滤噪音：如果只匹配了一个字符且是噪音字符
                if max_consecutive_match == 1 and len(keyword) == 1 and keyword in noise_chars:
                    score = 0
            else:
                # 有意义字符匹配
                meaningful_match_count = 0
                for char in keyword:
                    if char not in noise_chars and char in name_lower:
                        meaningful_match_count += 1
                
                if meaningful_match_count >= 1:
                    score += int(10 * (meaningful_match_count / len(keyword)))
        
        # 如果有匹配，添加到结果中
        if score > 0:
            results.append((p, score))
    
    # 按匹配度排序，匹配度相同时按名称排序
    sorted_results = sorted(results, key=lambda x: (-x[1], x[0].get('name', '')))
    return [p for p, _ in sorted_results]

@app.route('/api/cart', methods=['GET'])
def get_cart():
    """获取购物车"""
    try:
        # 优先从自定义请求头中获取用户名（由前端发送）
        username = request.headers.get('X-Username')
        if not username:
            # 回退：从Authorization头中提取（兼容旧逻辑）
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        # 获取用户的购物车
        user_cart = USER_CARTS.get(username, [])
        
        # 计算总价
        total = sum(item['price'] * item['quantity'] for item in user_cart)
        
        return jsonify({
            'success': True,
            'data': {
                'items': user_cart,
                'total': total
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/add', methods=['POST'])
def add_to_cart():
    """添加到购物车"""
    try:
        # 优先从自定义请求头中获取用户名
        username = request.headers.get('X-Username')
        if not username:
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        data = request.get_json()
        product_id = data.get('productId')
        quantity = data.get('quantity', 1)
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        # 查找商品
        product = next((p for p in REAL_PRODUCTS if p['id'] == product_id), None)
        if not product:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 获取或创建用户购物车
        if username not in USER_CARTS:
            USER_CARTS[username] = []
        
        # 检查商品是否已在购物车中
        existing_item = None
        for item in USER_CARTS[username]:
            if item['product_id'] == product_id:
                existing_item = item
                break
        
        if existing_item:
            # 更新数量
            existing_item['quantity'] += quantity
        else:
            # 添加新商品
            cart_item = {
                'product_id': product_id,
                'product_name': product['name'],
                'price': product['price'],
                'quantity': quantity,
                'selected': False,
                'image': product.get('image', ''),
                'category': product.get('category', '')
            }
            USER_CARTS[username].append(cart_item)
        
        # 保存购物车数据
        save_user_carts(USER_CARTS)
        
        return jsonify({
            'success': True,
            'data': {
                'message': '商品已添加到购物车',
                'product_id': product_id,
                'quantity': quantity
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/update', methods=['POST'])
def update_cart():
    """更新购物车商品数量"""
    try:
        # 优先从自定义请求头中获取用户名
        username = request.headers.get('X-Username')
        if not username:
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        data = request.get_json()
        product_id = data.get('productId')
        quantity = data.get('quantity', 1)
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        if username not in USER_CARTS:
            return jsonify({'success': False, 'error': '购物车为空'}), 404
        
        # 查找并更新商品
        for item in USER_CARTS[username]:
            if item['product_id'] == product_id:
                item['quantity'] = max(1, quantity)  # 最少1个
                save_user_carts(USER_CARTS)
                return jsonify({
                    'success': True,
                    'data': {
                        'message': '购物车已更新',
                        'product_id': product_id,
                        'quantity': item['quantity']
                    }
                })
        
        return jsonify({'success': False, 'error': '商品不在购物车中'}), 404
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/remove', methods=['POST'])
def remove_from_cart():
    """从购物车移除商品"""
    try:
        # 优先从自定义请求头中获取用户名
        username = request.headers.get('X-Username')
        if not username:
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        data = request.get_json()
        product_id = data.get('productId')
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        if username not in USER_CARTS:
            return jsonify({'success': False, 'error': '购物车为空'}), 404
        
        # 移除商品
        USER_CARTS[username] = [item for item in USER_CARTS[username] if item['product_id'] != product_id]
        save_user_carts(USER_CARTS)
        
        return jsonify({
            'success': True,
            'data': {
                'message': '商品已从购物车移除',
                'product_id': product_id
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/clear', methods=['POST'])
def clear_cart():
    """清空购物车"""
    try:
        # 从请求头获取用户token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({'success': False, 'error': '未登录'}), 401
        
        username = auth_header.replace('Bearer ', '')
        
        # 清空购物车
        USER_CARTS[username] = []
        save_user_carts(USER_CARTS)
        
        return jsonify({
            'success': True,
            'data': {
                'message': '购物车已清空'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders', methods=['GET'])
def get_orders():
    """获取用户订单"""
    try:
        # 获取用户信息
        auth_header = request.headers.get('Authorization')
        username = request.headers.get('X-Username')
        if not username and auth_header:
            username = auth_header.replace('Bearer ', '')
        
        if not username:
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 获取用户的订单
        user_orders = USER_ORDERS.get(username, [])
        
        return jsonify({
            'success': True,
            'data': {
                'orders': user_orders
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders/<order_id>', methods=['GET'])
def get_order_detail(order_id):
    """获取订单详情"""
    try:
        # 获取用户信息
        auth_header = request.headers.get('Authorization')
        username = request.headers.get('X-Username')
        if not username and auth_header:
            username = auth_header.replace('Bearer ', '')
        
        if not username:
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 查找订单
        user_orders = USER_ORDERS.get(username, [])
        order = next((o for o in user_orders if o['order_number'] == order_id), None)
        
        if not order:
            return jsonify({'success': False, 'error': '订单不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': order
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders/create', methods=['POST'])
def create_order():
    """创建订单"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['items', 'shippingAddress', 'paymentMethod']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 生成订单号
        order_number = f"ORD{int(datetime.now().timestamp())}{uuid.uuid4().hex[:6].upper()}"
        
        # 计算总金额并获取商品产地信息
        total_amount = 0
        origin_addresses = {}  # 统计每个产地的商品数量
        processed_items = []  # 处理后的订单项（包含产地信息）
        
        for item in data['items']:
            product = next((p for p in REAL_PRODUCTS if p['id'] == item['productId']), None)
            if product:
                total_amount += product['price'] * item['quantity']
                
                # 获取商品产地地址
                origin_address = product.get('location', '')
                
                # 添加到处理后的订单项（包含产地信息）
                processed_item = item.copy()
                if origin_address and origin_address != '未知产地':
                    processed_item['origin_address'] = origin_address
                    # 统计每个产地的商品数量
                    if origin_address not in origin_addresses:
                        origin_addresses[origin_address] = 0
                    origin_addresses[origin_address] += item['quantity']
                
                processed_items.append(processed_item)
        
        # 确定主发货地（商品数量最多的产地）
        if origin_addresses:
            main_origin_address = max(origin_addresses.items(), key=lambda x: x[1])[0]
            origin_count = len(origin_addresses)
        else:
            # 如果没有找到产地信息，使用默认仓库地址
            main_origin_address = DEFAULT_WAREHOUSE_ADDRESS
            origin_count = 1
        
        # 计算运费（使用物流计算模块）
        shipping_address = data['shippingAddress']
        delivery_address = f"{shipping_address.get('address', '')}"
        
        # 初始化物流相关变量
        logistics_error = None
        distance_km = None
        duration_h = None
        
        # 计算多发货地附加费
        multi_origin_fee = (origin_count - 1) * 3 if origin_count > 1 else 0
        
        if LOGISTICS_AVAILABLE:
            # 使用商品的实际产地地址计算运费
            logistics_result = calculate_shipping_fee_from_addresses(
                main_origin_address,
                delivery_address,
                use_api=True
            )
            
            base_shipping_fee = logistics_result['shipping_fee']
            distance_km = logistics_result.get('distance_km')
            duration_h = logistics_result.get('duration_h')
            logistics_error = logistics_result.get('error')
            
            # 总运费 = 基础运费 + 多发货地附加费
            shipping_fee = base_shipping_fee + multi_origin_fee
            
            if logistics_error:
                print(f"物流计算警告: {logistics_error}，使用默认运费")
        else:
            # 如果没有物流模块，使用默认运费
            base_shipping_fee = 15.00
            shipping_fee = base_shipping_fee + multi_origin_fee
            logistics_error = "物流计算模块未启用"
        
        total_amount += shipping_fee
        
        # 应用折扣
        discount = data.get('discount', 0)
        if discount > 0:
            total_amount = total_amount * (1 - discount / 100)
        
        # 计算预计送达时间（基于物流信息）
        if LOGISTICS_AVAILABLE:
            estimated_delivery_timestamp = calculate_estimated_delivery_time(
                distance_km=distance_km,
                duration_h=duration_h
            )
        else:
            # 如果没有物流模块，使用默认3天
            estimated_delivery_timestamp = datetime.now().timestamp() + 3 * 24 * 3600
        
        # 获取用户信息
        auth_header = request.headers.get('Authorization')
        username = request.headers.get('X-Username')
        if not username and auth_header:
            username = auth_header.replace('Bearer ', '')
        
        if not username:
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 创建订单数据
        order_data = {
            'order_number': order_number,
            'items': processed_items,  # 使用包含产地信息的订单项
            'shipping_address': data['shippingAddress'],
            'payment_method': data['paymentMethod'],
            'total_amount': round(total_amount, 2),
            'shipping_fee': shipping_fee,
            'multi_origin_fee': multi_origin_fee,  # 多发货地附加费
            'discount': discount,
            'status': 'Processing',
            'created_at': datetime.now().isoformat(),
            'estimated_delivery': estimated_delivery_timestamp,
            # 物流信息
            'logistics': {
                'distance_km': distance_km,
                'duration_h': duration_h,
                'warehouse_address': main_origin_address,  # 使用实际的主发货地地址
                'origin_addresses': list(origin_addresses.keys()),  # 所有发货地列表
                'origin_count': origin_count,  # 发货地数量
                'calculated': LOGISTICS_AVAILABLE and distance_km is not None,
                'error': logistics_error
            }
        }
        
        # 保存订单到用户订单列表
        if username not in USER_ORDERS:
            USER_ORDERS[username] = []
        
        USER_ORDERS[username].append(order_data)
        save_user_orders(USER_ORDERS)
        
        return jsonify({
            'success': True,
            'data': order_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/logistics/calculate', methods=['POST'])
def calculate_logistics():
    """计算物流运费"""
    try:
        data = request.get_json()
        delivery_address = data.get('delivery_address', '')
        
        if not delivery_address:
            return jsonify({'success': False, 'error': '请提供收货地址'}), 400
        
        if LOGISTICS_AVAILABLE:
            # 使用物流计算模块计算运费
            logistics_result = calculate_shipping_fee_from_addresses(
                DEFAULT_WAREHOUSE_ADDRESS,
                delivery_address,
                use_api=True
            )
            
            return jsonify({
                'success': True,
                'data': {
                    'shipping_fee': logistics_result['shipping_fee'],
                    'distance_km': logistics_result.get('distance_km'),
                    'duration_h': logistics_result.get('duration_h'),
                    'warehouse_address': DEFAULT_WAREHOUSE_ADDRESS,
                    'delivery_address': delivery_address,
                    'calculated': logistics_result['success'],
                    'error': logistics_result.get('error')
                }
            })
        else:
            return jsonify({
                'success': False,
                'error': '物流计算模块未启用',
                'data': {
                    'shipping_fee': 15.0,
                    'distance_km': None,
                    'duration_h': None,
                    'warehouse_address': DEFAULT_WAREHOUSE_ADDRESS,
                    'delivery_address': delivery_address,
                    'calculated': False
                }
            })
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/recommendations', methods=['GET'])
def get_recommendations():
    """获取推荐商品"""
    try:
        limit = int(request.args.get('limit', 10))
        
        # 返回热门商品
        recommendations = REAL_PRODUCTS[:limit]
        
        return jsonify({
            'success': True,
            'data': {
                'products': recommendations,
                'type': 'trending'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/categories', methods=['GET'])
def get_categories():
    """获取商品分类"""
    try:
        categories = [
            {'id': 'Food', 'name': '食品', 'icon': 'fas fa-utensils'},
            {'id': 'Clothing', 'name': '服装', 'icon': 'fas fa-tshirt'},
            {'id': 'Book', 'name': '图书', 'icon': 'fas fa-book'},
            {'id': 'Electronic Products', 'name': '电子产品', 'icon': 'fas fa-laptop'},
            {'id': 'Daily product', 'name': '日用品', 'icon': 'fas fa-home'}
        ]
        
        return jsonify({
            'success': True,
            'data': {
                'categories': categories
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({'success': False, 'error': '接口不存在'}), 404

# 卖家商品管理API
@app.route('/api/seller/products', methods=['GET'])
def get_seller_products():
    """获取卖家的商品列表"""
    try:
        username = request.args.get('username')
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_PRODUCTS:
            return jsonify({'success': True, 'data': {'products': []}})
        
        products = SELLER_PRODUCTS[username]
        return jsonify({
            'success': True,
            'data': {
                'products': products,
                'total': len(products)
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products', methods=['POST'])
def create_seller_product():
    """创建卖家商品"""
    try:
        data = request.get_json()
        username = data.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        # 验证必要字段
        required_fields = ['name', 'price', 'category', 'location', 'stock']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 生成商品ID
        product_id = f"SP{int(datetime.now().timestamp())}{username[:3].upper()}"
        
        # 创建商品数据
        product_data = {
            'id': product_id,
            'name': data['name'],
            'price': float(data['price']),
            'category': data['category'],
            'location': data['location'],
            'stock': int(data['stock']),
            'description': data.get('description', f"优质{data['name']}，产地{data['location']}"),
            'image': data.get('image', f"https://via.placeholder.com/300x200?text={data['name']}"),
            'merchant_id': username,
            'created_at': datetime.now().isoformat(),
            'status': 'active'
        }
        
        # 保存商品
        if username not in SELLER_PRODUCTS:
            SELLER_PRODUCTS[username] = []
        
        SELLER_PRODUCTS[username].append(product_data)
        
        if save_seller_products(SELLER_PRODUCTS):
            return jsonify({
                'success': True,
                'data': product_data
            })
        else:
            return jsonify({'success': False, 'error': '保存商品失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products/<product_id>', methods=['PUT'])
def update_seller_product(product_id):
    """更新卖家商品"""
    try:
        data = request.get_json()
        username = data.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_PRODUCTS:
            return jsonify({'success': False, 'error': '用户没有商品'}), 404
        
        # 查找商品
        products = SELLER_PRODUCTS[username]
        product_index = None
        for i, product in enumerate(products):
            if product['id'] == product_id:
                product_index = i
                break
        
        if product_index is None:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 更新商品信息
        updated_product = products[product_index].copy()
        for key, value in data.items():
            if key not in ['username', 'id', 'created_at']:
                updated_product[key] = value
        
        updated_product['updated_at'] = datetime.now().isoformat()
        products[product_index] = updated_product
        
        if save_seller_products(SELLER_PRODUCTS):
            return jsonify({
                'success': True,
                'data': updated_product
            })
        else:
            return jsonify({'success': False, 'error': '更新商品失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products/<product_id>', methods=['DELETE'])
def delete_seller_product(product_id):
    """删除卖家商品"""
    try:
        username = request.args.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_PRODUCTS:
            return jsonify({'success': False, 'error': '用户没有商品'}), 404
        
        # 查找并删除商品
        products = SELLER_PRODUCTS[username]
        product_index = None
        for i, product in enumerate(products):
            if product['id'] == product_id:
                product_index = i
                break
        
        if product_index is None:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        deleted_product = products.pop(product_index)
        
        if save_seller_products(SELLER_PRODUCTS):
            return jsonify({
                'success': True,
                'data': {'message': '商品删除成功', 'product': deleted_product}
            })
        else:
            return jsonify({'success': False, 'error': '删除商品失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# 卖家店铺管理API
@app.route('/api/seller/shop', methods=['GET'])
def get_seller_shop():
    """获取卖家店铺信息"""
    try:
        username = request.args.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_SHOPS:
            return jsonify({'success': False, 'error': '店铺不存在'}), 404
        
        shop_info = SELLER_SHOPS[username]
        return jsonify({
            'success': True,
            'data': shop_info
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/shop', methods=['PUT'])
def update_seller_shop():
    """更新卖家店铺信息"""
    try:
        data = request.get_json()
        username = data.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_SHOPS:
            return jsonify({'success': False, 'error': '店铺不存在'}), 404
        
        # 更新店铺信息
        shop_info = SELLER_SHOPS[username].copy()
        for key, value in data.items():
            if key not in ['username', 'shop_id', 'owner_username', 'created_at']:
                shop_info[key] = value
        
        shop_info['updated_at'] = datetime.now().isoformat()
        SELLER_SHOPS[username] = shop_info
        
        if save_seller_shops(SELLER_SHOPS):
            return jsonify({
                'success': True,
                'data': shop_info
            })
        else:
            return jsonify({'success': False, 'error': '更新店铺信息失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# 卖家统计API
@app.route('/api/seller/stats', methods=['GET'])
def get_seller_stats():
    """获取卖家统计数据"""
    try:
        username = request.args.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        # 获取商品统计
        products = SELLER_PRODUCTS.get(username, [])
        total_products = len(products)
        
        # 计算总销售额（模拟数据）
        total_revenue = sum(product['price'] * product['stock'] for product in products) * 0.1
        
        # 计算平均评分
        avg_rating = 4.5 if products else 0
        
        stats = {
            'total_products': total_products,
            'total_revenue': round(total_revenue, 2),
            'avg_rating': avg_rating,
            'total_orders': 0,  # 模拟数据
            'pending_orders': 0,
            'completed_orders': 0
        }
        
        return jsonify({
            'success': True,
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({'success': False, 'error': '接口不存在'}), 404

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({'success': False, 'error': '服务器内部错误'}), 500

if __name__ == '__main__':
    print("="*60)
    print("阿里宝宝电商平台 - Web API服务器（简化版）")
    print("="*60)
    print("正在启动服务器...")
    print("API文档:")
    print("  POST /api/auth/login - 用户登录")
    print("  POST /api/auth/register - 用户注册")
    print("  GET  /api/products - 获取商品列表")
    print("  GET  /api/products/<id> - 获取商品详情")
    print("  POST /api/products/search - 搜索商品")
    print("  GET  /api/cart - 获取购物车")
    print("  POST /api/cart/add - 添加到购物车")
    print("  GET  /api/orders - 获取订单")
    print("  POST /api/orders/create - 创建订单")
    print("  GET  /api/recommendations - 获取推荐商品")
    print("  GET  /api/categories - 获取商品分类")
    print("  GET  /api/seller/products - 获取卖家商品列表")
    print("  POST /api/seller/products - 创建卖家商品")
    print("  PUT  /api/seller/products/<id> - 更新卖家商品")
    print("  DELETE /api/seller/products/<id> - 删除卖家商品")
    print("  GET  /api/seller/shop - 获取卖家店铺信息")
    print("  PUT  /api/seller/shop - 更新卖家店铺信息")
    print("  GET  /api/seller/stats - 获取卖家统计数据")
    print("="*60)
    print("服务器地址: http://localhost:8000")
    print("测试账号: admin / 123456")
    print("="*60)
    
    # 启动Flask服务器
    app.run(
        host='0.0.0.0',
        port=8000,
        debug=True,
        threaded=True
    )
